'use strict';
define(['jquery','angular','ocLazyLoad'],function($,angular){
	angular.module('app.u2frame', ['oc.lazyLoad'])	

	//在客户区动态创建tab（使用ng-include作为容器）
	.controller('u2frameCtrl', [ '$rootScope', '$scope', '$ocLazyLoad', function($rootScope, $scope, $ocLazyLoad){
		
		//左侧栏的控制器，主要是鼠标点击动作响应///////////////////////////////////////////////
		//控制器启动时定义一个窗口列表
		
        //窗口列表数据中的数据
		$rootScope.wins = new Array();
		
		//全局函数（设置当前活动窗口）
		$rootScope.setCurrent = function(winid,winname,path,winParams) {
			$rootScope.winid = winid;
			$rootScope.winname = winname;
			$rootScope.path = path;
			$rootScope.winParams = winParams;
		}
		
		/*
		//初始化首页的数据，改到由函数进行初始化，在主控制器中
		//全局变量
		//设置当前窗口信息
		$rootScope.setCurrent('home','首页','/appcenter/home/center','传递给窗口的参数！');
        //增加窗口列表数据中的数据
		var win = {};
		win.winid = $rootScope.winid
		win.winname = $rootScope.winname;
		win.path = $rootScope.path;
		win.winParams = $rootScope.winParams;
		$rootScope.wins.push(win);
		*/
		
		/*
		$rootScope.menuClick = function(url,name,winParams) {
			//首先判断是否已经在列表中存在
			var winid = null;
			for(var i=0; i<$rootScope.wins.length;i++){
				if(url==$rootScope.wins[i].path){
					//将当前窗口ID设为此id
					winid = $rootScope.wins[i].winid;
				}
			}
			
			if(winid==null){
				//不存在，则新建
				winid=common.getGUID();
				$rootScope.createTab(winid,name,url,winParams);
				//窗口已经存在，则激活当前窗口
				$rootScope.activeTab(winid,winParams);
			}else{
				//窗口已经存在，则激活当前窗口
				$rootScope.activeTab(winid,winParams);
			}

		};
		*/
		
		//打开窗口
		$rootScope.menuClick = function(appid,url,name,winParams) {
            
			console.log('menuClick.appid-->',appid);
			console.log('menuClick.url-->',url);
//			console.log('menuClick.name-->',name);
//			console.log('menuClick.winParams-->',winParams);
			console.log('menuClick.$rootScope.wins-->',$rootScope.wins);
			
			//var jsFile = 'baseinfonfo/fileFactory/list';
//			var jsFile = $rootScope.getProjectName() + url;//使用这个需要加入文件后缀名
			
			var jsFile;// = 'js' + url;
//			if($rootScope.currentModule.value == 'appId'){
//				//ERP
//				jsFile = 'js' + url;
//			}else{
//				//ERP以外
//				jsFile = '../' + 'js' + url;
//			}
			jsFile = 'js' + url;
			
			console.log('jsFile-->',jsFile);
			
	        $ocLazyLoad.load(jsFile).then(function(s,s1) {
	            //console.log('$ocLazyLoad.s-->',s);
	            //console.log('$ocLazyLoad.s1-->',s1);
				//$scope.partialUrl = 'partials/grid.html';
				
				/*
    			require(['/appcenter/js' + url + '1.js'],function(obj){
    				console.log(obj);
//    				var injector = angular.injector('app.controllers');
//    				injector.instantiate(obj);
    			});
    			*/

		        //var path = $rootScope.getProjectName() + url;
				var path = url;

				//首先判断是否已经在列表中存在
				var winid = null;
				for(var i=0; i<$rootScope.wins.length;i++){
					if(path==$rootScope.wins[i].path){
						//将当前窗口ID设为此id
						winid = $rootScope.wins[i].winid;
					}
				}
				//console.log('winid-->>',winid);
				if(winid==null){
					//不存在，则新建
					//winid=common.getGUID();
					winid = appid;
					$rootScope.createTab(winid,name,path,winParams);
				}
				//窗口已经存在，则激活当前窗口
				$rootScope.activeTab(winid,winParams);
				
	        }, function(e) {
	            console.log('$ocLazyLoad.e-->',e);
          		alert("文件加载失败。请检查服务器是否启动，或者网络连接是否存在问题！");
	        });
	
		};
		
		//打开中心窗口
		$rootScope.loadCenter = function() {
			//appid,url,name,winParams
			var appid = 'home';
			var url = '/center/center';
			var name = '首页';
			var winParams = '传递给窗口的参数！';
			
			var jsFile = 'js' + url;
			
			console.log('jsFile-->',jsFile);
			
	        $ocLazyLoad.load(jsFile).then(function(s,s1) {
				var path = url;

				//首先判断是否已经在列表中存在
				var winid = null;
				for(var i=0; i<$rootScope.wins.length;i++){
					if(path==$rootScope.wins[i].path){
						//将当前窗口ID设为此id
						winid = $rootScope.wins[i].winid;
					}
				}
				//console.log('winid-->>',winid);
				if(winid==null){
					//不存在，则新建
					//winid=common.getGUID();
					winid = appid;
					$rootScope.createTab(winid,name,path,winParams);
				}
				//窗口已经存在，则激活当前窗口
				$rootScope.activeTab(winid,winParams);
				
	        }, function(e) {
	            console.log('$ocLazyLoad.e-->',e);
          		alert("文件加载失败。请检查服务器是否启动，或者网络连接是否存在问题！");
	        });
	
		};
		
		//关闭当前子窗口
		$rootScope.closeCurrentWindow = function() {
			$rootScope.removeTab($rootScope.winid)
		};
		

		
	}])
	
	.directive("u2frame",['$rootScope','$compile', function($rootScope,$compile){
		return {
			restrict:'A'
			,scope: {
//				winid:'=',
//				path:'=',
//				winname:'=',
//				state:'=',
//				wins:'=',
//				clicks:'=',
//				page:'='
			}
			,controller:'u2frameCtrl'
			//,templateUrl:'WEB-INF/v/security/home/_header.jsp'
			//,template:'<div>hello......</div>'
			//,templateUrl:'/test/header.jsp'
	//		,templateUrl:'/_header.jsp'
	//		,replace:true
			,link:function(scope,element,attr){
				
				function closeBtnClick(event){
			    	$rootScope.removeTab(event.data);
					//这是jQuery绑定的事件，所以需要使用下面的调用
			    	scope.$apply();
				}
				
				function tabnavliaClick(event){
//					event.preventDefault();
//					event.stopPropagation();
			    	var winid = event.data;
			    	/*
			        //设置当前窗口信息
					for(var i=0; i<$rootScope.wins.length;i++){
						if(winid==$rootScope.wins[i].winid){
							//设置当前窗口信息
							$rootScope.setCurrent(winid,$rootScope.wins[i].winname,$rootScope.wins[i].path);
						}
					}
					*/
			    	$rootScope.activeTab(winid);
					//这是jQuery绑定的事件，所以需要使用下面的调用
			    	scope.$apply();

				}
				
				$rootScope.createTab = function(winid,winname,path,winParams){
//					console.log('createTab.path-->',path);
			    	var tabnavid=winid;
			    	var tabcontentid=winid+'c';
			        //创建tab
			        var tabnav=$('#tabnav');
			        var tabnavli=$('<li role="presentation"></li>');
			        tabnavli.attr('id',tabnavid);
			        var tabnavlia=$("<a href=\"#" + tabcontentid + "\" aria-controls=\"" + tabcontentid + "\" role=\"tab\" data-toggle=\"tab\">" + winname + "</a>");
			        var closebtn=$("<button type=\"button\" class=\"close\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>");
			        tabnavli.appendTo(tabnav);
			        tabnavlia.appendTo(tabnavli);
			        closebtn.appendTo(tabnavlia);
			        //关闭按钮的click事件绑定
			        closebtn.bind('click',winid,closeBtnClick);
			        //导航标签a的click事件绑定
			        tabnavlia.bind('click',winid,tabnavliaClick);
			        /*
			        tabnavlia.on('shown.bs.tab', function (e) {
			        	  e.target // newly activated tab
			        	  e.relatedTarget // previous active tab
			        	  var winid = $(e.target).parent().attr('id');
					      $rootScope.activeTab(winid);
			        	})
			        */	
			        //scope.$apply();不能使用
//			        $compile(tabnavli.contents())(scope);

			      	var fullpath = $rootScope.getProjectName() + $rootScope.viewprefix + path + $rootScope.viewsuffix;
			        var src = "'" + fullpath + "'";
//			        console.log('createTab.src-->',src);
			        //创建tab内容
//			        var c = '<div role="tabpanel" style="overflow:auto;">'+path
//	        		+'<div ng-include src="getUrl()"></div>'
//	        		+'</div>';
			        var c = '<div role="tabpanel" style="overflow:auto;">'
	        		+'<div ng-include src="'+src+'"></div>'
	        		+'</div>';

			        var tabcontent=$('#tabcontent');
			        var tabcontentdiv=$(c);
			        tabcontentdiv.attr('id',tabcontentid);
			        tabcontentdiv.addClass('tab-pane')
			        tabcontentdiv.appendTo(tabcontent);

//			        tabcontentdiv.html(scope.page);
//			        tabcontentdiv.load(path);
			        $compile(tabcontentdiv.contents())(scope);
			        
			        //增加窗口列表数据中的数据
					var win = {};
					win.winid = winid
					win.winname = winname;
					win.path = path;
					win.winParams = winParams;
					
					$rootScope.wins.push(win);
					//设置当前窗口信息
//					$rootScope.winid = winid;
//					$rootScope.winname = winname;
//					$rootScope.path = path;
					/*利用单独的激活函数激活，不在创建时激活
			        //激活tab页
			        $('#tabnav a[href="#'+tabcontentid+'"]').tab('show');
					//设置当前窗口信息
					$rootScope.setCurrent(winid,winname,path);
					*/
			    };
			    
//			    scope.activeTab = function(winid){
//			    	$rootScope.activeTab(winid);
//			    }
			    
			    $rootScope.activeTab = function(winid,winParams){
//					var winParams = {h:123};
//					$rootScope.winParams = winParams;
//					console.log('窗口激活时设定的参数1');

			    	var tabnavid=winid;
			    	var tabcontentid=winid+'c';
			        //激活tab页
			        $('#tabnav a[href="#'+tabcontentid+'"]').tab('show');
			        //设置当前窗口信息
					for(var i=0; i<$rootScope.wins.length;i++){
						if(winid==$rootScope.wins[i].winid){
							//设置当前窗口信息
//							$rootScope.winid = winid;
//							$rootScope.winname = $rootScope.wins[i].winname;
//							$rootScope.path = $rootScope.wins[i].path;
							//修改参数
							$rootScope.wins[i].winParams = winParams;
							//设置当前窗口
							$rootScope.setCurrent(winid,$rootScope.wins[i].winname,$rootScope.wins[i].path,winParams);
							//广播当前窗口被激活事件
							
//							if($rootScope.wins[i].winid=='home'){
//								$rootScope.$broadcast('activeTab',$rootScope.wins[i]);
//							}
							$rootScope.$broadcast('activeTab',$rootScope.wins[i]);
						}
					}
					
//					console.log('$rootScope.winParams-->',$rootScope.winParams);

			    };
			    
			    $rootScope.removeTab = function (winid){
			    	var tabcontentid=winid+'c';
//		        	//删除tab content
//		        	var tabnavlia = $(this).parent();
		        	var tabnavlia = $('#tabnav a[href="#' + tabcontentid + '"]');
		        	var tabnavli =  tabnavlia.parent();
		        	$(tabnavlia.attr('href')).remove();
			    	//删除tab nav li
//		        	var tabnavli =  $(this).parent().parent();
//		        	var tabnavliid = tabnavli.attr('id');
		        	tabnavli.remove();
			        //清楚窗口列表中的项目
					for(var i=0; i<$rootScope.wins.length;i++){
						if(winid==$rootScope.wins[i].winid){
							//存在，移除
							$rootScope.wins.splice(i,1);
							//删除之后当前窗口信息设置
							if(i>$rootScope.wins.length - 1){
								var winid = $rootScope.wins[$rootScope.wins.length - 1].winid;
								$rootScope.activeTab(winid);
							}else{
								var winid = $rootScope.wins[i].winid;
								$rootScope.activeTab(winid);
							}
							break;
						}
					}
		        	//显示首页
//			        $('#tabnav a[href="#home"]').tab('show');

			    	
			    };
			    
			    
			    
			}
		}
	}])

	 
});//define结束

